<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .parent {
        width: 300px;
        height: 200px;
        background-color: aqua;
      }
      .child {
        width: 200px;
        height: 100px;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div class="parent">
      <div class="child">please click me!</div>
    </div>
  </body>
  <script>
    // 获取DOM
    var parent = document.getElementsByClassName("parent")[0];
    var child = document.getElementsByClassName("child")[0];

    // child
    child.addEventListener(
      "click",
      function (e) {
        // 兼容event
        var e = e || window.event;
        // 阻止事件冒泡兼容写法
        e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
        console.log("child");
      },
      false
    ); //false:事件冒泡 true：事件捕获

    // parent
    parent.addEventListener(
      "click",
      function (e) {
        // 不考虑兼容
        e.stopPropagation();
        console.log("parent");
      },
      false
    );

    // body
    document.body.addEventListener(
      "click",
      function () {
        console.log("body");
      },
      false
    );

    // document
    document.addEventListener(
      "click",
      function () {
        console.log("document");
      },
      false
    );

    // window
    window.addEventListener(
      "click",
      function () {
        console.log("window");
      },
      false
    );
  </script>
</html>
